package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.atguigu.gulimall.product.vo.Catelog3Vo;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    public Long[] getCatelogPath(Long catelogId) {
        List<Long> cateList = Lists.newArrayList();
        getParentIdByCatelogId(catelogId, cateList);

        Collections.reverse(cateList);

        return cateList.toArray(new Long[cateList.size()]) ;
    }

    /**
     * 级联更新所有数据			[分区名默认是就是缓存的前缀] SpringCache: 不加锁
     *
     * @CacheEvict: 缓存失效模式		--- 页面一修改 然后就清除这两个缓存
     * key = "'getLevel1Categorys'" : 记得加单引号 [子解析字符串]
     *
     * @Caching: 同时进行多种缓存操作
     *
     * @CacheEvict(value = {"category"}, allEntries = true) : 删除这个分区所有数据
     *
     * @CachePut: 这次查询操作写入缓存
     */
//	@Caching(evict = {
//			@CacheEvict(value = {"category"}, key = "'getLevel1Categorys'"),
//			@CacheEvict(value = {"category"}, key = "'getCatelogJson'")
//	})
    @CacheEvict(value = {"category"}, allEntries = true)
//	@CachePut
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
//        this.updateById(category);
//        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    @CacheEvict(value = "category", allEntries = true)
    public void testCachEvit() {

    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public List<CategoryEntity> getLevel1Catagories() {
        System.out.println("getLevel1Categorys查询了数据库");
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        System.out.println("getCatelogJson查询了数据库");
        // 先查缓存在查数据库
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        // 查询所有一级分类
        List<CategoryEntity> level1 = getCategoryEntities(entityList, 0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 拿到每一个一级分类 然后查询他们的二级分类
            List<CategoryEntity> entities = getCategoryEntities(entityList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), l2.getName(), l2.getCatId().toString(), null);
                    // 找当前二级分类的三级分类
                    List<CategoryEntity> level3 = getCategoryEntities(entityList, l2.getCatId());
                    // 三级分类有数据的情况下
                    if (level3 != null) {
                        List<Catelog3Vo> catalog3Vos = level3.stream().map(l3 -> new Catelog3Vo(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString())).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> entityList, long parentId) {
        return entityList.stream().filter(t -> Objects.equals(t.getParentCid(), parentId)).collect(Collectors.toList());
    }

    private void getParentIdByCatelogId(Long catelogId, List<Long> catelogIds) {
        CategoryEntity categoryEntity = super.baseMapper.selectById(catelogId);
        if (categoryEntity != null) {
            catelogIds.add(categoryEntity.getCatId());
        }

        if (categoryEntity.getParentCid() != 0) {
            getParentIdByCatelogId(categoryEntity.getParentCid(), catelogIds);
        }
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> parentList = categoryEntities.stream()
            .filter(t -> t.getParentCid() == 0)
            .map(t -> {
                t.setChildren(getSubMenus(t, categoryEntities));
                return t;
            })
            .sorted(Comparator.comparing(CategoryEntity::getSort))
            .collect(Collectors.toList());

        return parentList;
    }

    private List<CategoryEntity> getSubMenus(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        if (categoryEntity == null) {
            return null;
        }

        List<CategoryEntity> subMenus = categoryEntities.stream()
            .filter(t -> Objects.equals(t.getParentCid(), categoryEntity.getCatId()))
            .map(t -> {
                if (categoryEntity.getCatLevel() == 3) {
                    t.setChildren(null);
                    return t;
                } else {
                    t.setChildren(getSubMenus(t, categoryEntities));
                    return t;
                }
            }).sorted(Comparator.comparing(CategoryEntity::getSort))
            .collect(Collectors.toList());

        return subMenus;
    }

}